package com.zhenmaitang.clinic_sys.service.impl;

import com.zhenmaitang.clinic_sys.entity.Role;
import com.zhenmaitang.clinic_sys.entity.User;
import com.zhenmaitang.clinic_sys.entity.UserRole;
import com.zhenmaitang.clinic_sys.dto.UserRegistrationRequest;
import com.zhenmaitang.clinic_sys.mapper.UserMapper;
import com.zhenmaitang.clinic_sys.service.UserService;
import com.zhenmaitang.clinic_sys.service.UserRoleService;
import com.zhenmaitang.clinic_sys.service.RoleService;
import com.zhenmaitang.clinic_sys.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;

import javax.naming.Name;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;
    
    @Autowired
    private PermissionService permissionService;

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public User createUser(UserRegistrationRequest request) {
        // 检查用户名和邮箱是否已存在
        if (existsByUsername(request.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        if (existsByEmail(request.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }

        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setEmail(request.getEmail());
        user.setFullName(request.getFullName());
        user.setRole(request.getRole());
        user.setEnabled(true);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        userMapper.insert(user);
        return user;
    }

    @Override
    public User updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
        return user;
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userMapper.existsByUsername(username);
    }

    @Override
    public boolean existsByEmail(String email) {
        return userMapper.existsByEmail(email);
    }

    @Override
    public List<User> findUsersByDepartment(Integer departmentId) {
        return userMapper.findByDepartmentId(departmentId);
    }

    @Override
    public List<User> findUsersByRole(String role) {
        // 这里需要通过user_roles关联表查询，简化实现
        throw new UnsupportedOperationException("该方法需要通过user_roles关联表重实现");
    }

    @Override
    public void assignRoleToUser(Integer userId, Integer roleId, Integer departmentId) {
        UserRole userRole = new UserRole(userId, roleId, departmentId);
        userRoleService.createUserRole(userRole);
    }

    @Override
    public User createUserDirectly(User user) {
        // 检查用户名和邮箱是否已存在
        if (existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        if (existsByEmail(user.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }

        userMapper.insert(user);
        return user;
    }

    @Override
    public List<Role> getUserRoles(Integer userId) {
        List<UserRole> userRoles = userRoleService.getUserRolesByUserId(userId);
        List<Role> roles = new java.util.ArrayList<>();
        for (UserRole userRole : userRoles) {
            roles.add(roleService.getRoleById(userRole.getRoleId()));
        }
        return roles;
    }

    @Override
    public void assignRolesToUser(Integer userId, List<Integer> roleIds, Integer departmentId) {
        // 先删除用户现有的所有角色
        userRoleService.deleteByUserId(userId);
        
        // 然后分配新的角色
        for (Integer roleId : roleIds) {
            UserRole userRole = new UserRole(userId, roleId, departmentId);
            userRoleService.createUserRole(userRole);
        }
    }

    @Override
    public List<String> getUserPermissions(Integer userId) {
        List<Role> roles = getUserRoles(userId);
        List<String> permissions = new java.util.ArrayList<>();
        for (Role role : roles) {
            // 这里简化处理，实际应该解析角色的permissions字段
            permissions.add(role.getName());
        }
        return permissions;
    }

    @Override
    public boolean hasPermission(Integer userId, String permissionCode) {
        // 根据用户ID获取用户信息
        User user = findById(userId);
        if (user == null || !user.getEnabled()) {
            return false;
        }
        
        // 获取用户的所有角色
        List<Role> roles = getUserRoles(userId);
        if (roles.isEmpty()) {
            return false;
        }
        
        // 检查用户的所有角色是否有指定权限
        for (Role role : roles) {
            Set<String> rolePermissions = permissionService.getPermissionsByRoleName(role.getName());
            if (rolePermissions.contains(permissionCode)) {
                return true;
            }
        }
        return false;
    }
}